<template>
  <div class="slider-verify-container">
    <!-- 头部插槽 -->
    <div v-if="$slots.header" class="slider-header">
      <slot name="header"></slot>
    </div>

    <div class="slider-track" ref="sliderTrack">
      <!-- 进度条背景 -->
      <div
        class="slider-progress"
        :style="{
          width: progressWidth + 'px',
          background: isSuccess ? successColor : progressColor
        }"
      ></div>

      <!-- 进度条内容插槽 -->
      <div v-if="$slots['progress-content']" class="progress-content">
        <slot name="progress-content" :progress="progress" :is-success="isSuccess"></slot>
      </div>

      <!-- 提示文字或插槽 -->
      <div class="slider-text" :class="{ 'text-success': isSuccess }">
        <slot v-if="isSuccess" name="success">
          {{ successText }}
        </slot>
        <slot v-else name="default">
          {{ text }}
        </slot>
      </div>

      <!-- 滑块按钮 -->
      <div
        class="slider-button"
        :class="{
          'slider-success': isSuccess,
          'slider-dragging': isDragging,
          'slider-disabled': props.disabled || botDetected
        }"
        :style="{
          transform: `translateX(${sliderLeft}px)`,
          background: isSuccess ? buttonSuccessColor : buttonColor,
          borderColor: isSuccess
            ? buttonSuccessBorderColor
            : isDragging
              ? buttonActiveBorderColor
              : buttonBorderColor
        }"
        @mousedown="handleMouseDown"
        @touchstart="handleTouchStart"
      >
        <slot
          name="icon"
          :is-success="isSuccess"
          :is-dragging="isDragging"
          :is-disabled="props.disabled || botDetected"
        >
          <svg
            class="slider-icon"
            :class="{ rotating: isDragging }"
            viewBox="0 0 1024 1024"
            width="16"
            height="16"
          >
            <path
              v-if="isSuccess"
              d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 0 0-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1 0.4-12.8-6.3-12.8z"
              fill="currentColor"
            />
            <path
              v-else
              d="M869 487.8L491.2 159.9c-2.9-2.5-6.6-3.9-10.5-3.9h-88.5c-7.4 0-10.4 9.7-4.2 14.2l350 304.1L390.2 779c-6.1 4.6-3.1 14.2 4.2 14.2h91.5c3.9 0 7.6-1.4 10.5-3.9L869 461.7c6.3-5.3 6.3-14.6 0-19.9z"
              fill="currentColor"
            />
          </svg>
        </slot>
      </div>

      <!-- 轨道装饰插槽 -->
      <div v-if="$slots['track-decoration']" class="track-decoration">
        <slot
          name="track-decoration"
          :progress="progress"
          :is-success="isSuccess"
          :is-dragging="isDragging"
        ></slot>
      </div>
    </div>

    <!-- 机器人检测提示 -->
    <transition name="bot-warning" appear>
      <div v-if="botDetected" class="bot-warning">
        <slot
          name="bot-warning"
          :reason="botDetectionReason"
          :retry-count="retryCount"
          :max-retries="props.allowedRetries"
          :remaining-retries="props.allowedRetries - retryCount"
          :detection-data="getBotDetectionData()"
        >
          <div class="default-bot-warning">
            <i class="warning-icon">⚠️</i>
            <span>检测到异常行为，请重新验证 ({{ retryCount }}/{{ props.allowedRetries }})</span>
          </div>
        </slot>
      </div>
    </transition>

    <!-- 底部信息插槽 -->
    <div v-if="$slots.footer || showProgress" class="slider-footer">
      <slot
        name="footer"
        :progress="progress"
        :is-success="isSuccess"
        :is-dragging="isDragging"
        :retry-count="retryCount"
        :bot-detected="botDetected"
      >
        <div v-if="showProgress" class="progress-info">
          <span class="progress-text">进度: {{ Math.round(progress) }}%</span>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progress + '%' }"></div>
          </div>
        </div>
      </slot>
    </div>

    <!-- 帮助信息插槽 -->
    <div v-if="$slots.help || showHelp" class="slider-help">
      <slot
        name="help"
        :bot-detected="botDetected"
        :retry-count="retryCount"
        :is-success="isSuccess"
      >
        <div v-if="showHelp" class="help-content">
          <i class="help-icon">💡</i>
          <span>{{ getHelpText() }}</span>
        </div>
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue'

interface Props {
  text?: string
  successText?: string
  width?: number
  height?: number
  disabled?: boolean
  // 显示选项
  showProgress?: boolean // 显示进度条
  showHelp?: boolean // 显示帮助信息
  // 颜色配置
  trackColor?: string // 轨道背景色
  progressColor?: string // 进度条颜色
  successColor?: string // 成功时进度条颜色
  buttonColor?: string // 按钮背景色
  buttonSuccessColor?: string // 成功时按钮背景色
  buttonBorderColor?: string // 按钮边框色
  buttonActiveBorderColor?: string // 拖拽时按钮边框色
  buttonSuccessBorderColor?: string // 成功时按钮边框色
  textColor?: string // 文字颜色
  successTextColor?: string // 成功时文字颜色
  // 验证配置
  threshold?: number // 验证通过的阈值（百分比）
  // 防机器人配置
  enableBotDetection?: boolean // 是否启用机器人检测
  minDragTime?: number // 最小拖拽时间（毫秒）
  maxDragTime?: number // 最大拖拽时间（毫秒）
  minTrackPoints?: number // 最少轨迹点数
  allowedRetries?: number // 允许重试次数
  // 增强配置
  resetOnFail?: boolean // 失败时是否自动重置
  autoReset?: boolean // 成功后是否自动重置
  autoResetDelay?: number // 自动重置延迟时间（毫秒）
  vibrationFeedback?: boolean // 是否启用震动反馈（移动端）
  soundFeedback?: boolean // 是否启用声音反馈
}

interface Emits {
  (e: 'success'): void
  (e: 'fail'): void
  (e: 'change', value: number): void
  (e: 'bot-detected', reason: string, data: any): void
  (e: 'start-drag'): void
  (e: 'end-drag'): void
  (e: 'reset'): void
  (e: 'retry', count: number): void
}

interface TrackPoint {
  x: number
  y: number
  timestamp: number
  deltaTime: number
  velocity: number
  acceleration?: number
}

const props = withDefaults(defineProps<Props>(), {
  text: '请拖动滑块完成验证',
  successText: '验证成功',
  width: 300,
  height: 42,
  disabled: false,
  showProgress: false,
  showHelp: false,
  // 默认颜色配置
  trackColor: '#f7f9fa',
  progressColor: 'linear-gradient(90deg, #36d1dc 0%, #5b86e5 100%)',
  successColor: 'linear-gradient(90deg, #67c23a 0%, #85ce61 100%)',
  buttonColor: '#fff',
  buttonSuccessColor: '#67c23a',
  buttonBorderColor: '#dcdfe6',
  buttonActiveBorderColor: '#409eff',
  buttonSuccessBorderColor: '#67c23a',
  textColor: '#909399',
  successTextColor: '#fff',
  threshold: 90,
  // 防机器人默认配置
  enableBotDetection: true,
  minDragTime: 50,
  maxDragTime: 30000,
  minTrackPoints: 10,
  allowedRetries: 3,
  // 增强配置默认值
  resetOnFail: true,
  autoReset: false,
  autoResetDelay: 3000,
  vibrationFeedback: true,
  soundFeedback: false
})

const emit = defineEmits<Emits>()

// 组件状态
const sliderTrack = ref<HTMLElement>()
const sliderLeft = ref(0)
const isDragging = ref(false)
const isSuccess = ref(false)
const startX = ref(0)
const trackWidth = ref(0)
const buttonWidth = ref(42)
const initialMouseX = ref(0)

// 防机器人检测状态
const botDetected = ref(false)
const retryCount = ref(0)
const dragStartTime = ref(0)
const dragEndTime = ref(0)
const trackPoints = ref<TrackPoint[]>([])
const lastPosition = ref({ x: 0, y: 0 })
const componentMountTime = ref(0)
const userInteractionStarted = ref(false)
const hasActuallyDragged = ref(false)
const botDetectionReason = ref('')

// 计算属性
const progressWidth = computed(() => {
  return Math.min(sliderLeft.value + buttonWidth.value, trackWidth.value)
})

const progress = computed(() => {
  const maxLeft = trackWidth.value - buttonWidth.value
  return maxLeft > 0 ? (sliderLeft.value / maxLeft) * 100 : 0
})

// 获取帮助文本
const getHelpText = () => {
  if (botDetected.value) {
    const remaining = props.allowedRetries - retryCount.value
    return remaining > 0
      ? `请以正常速度拖动，剩余重试次数: ${remaining}`
      : '重试次数已用完，请稍后再试'
  }
  if (isSuccess.value) {
    return '验证成功！'
  }
  if (isDragging.value) {
    return '继续拖动到最右侧'
  }
  return '拖动滑块至最右侧完成验证'
}

// 震动反馈
const vibrate = (pattern: number | number[] = 100) => {
  if (props.vibrationFeedback && navigator.vibrate) {
    navigator.vibrate(pattern)
  }
}

// 声音反馈
const playSound = (type: 'success' | 'fail' | 'warning') => {
  if (!props.soundFeedback) return

  // 创建音频上下文和音调
  const audioContext = new (window.AudioContext || (window as any).webkitAudioContext)()
  const oscillator = audioContext.createOscillator()
  const gainNode = audioContext.createGain()

  oscillator.connect(gainNode)
  gainNode.connect(audioContext.destination)

  // 根据类型设置不同的音调
  const frequencies = {
    success: [523, 659, 784], // C-E-G 和弦
    fail: [330, 262], // E-C 下行
    warning: [440] // A 音
  }

  const freq = frequencies[type]
  oscillator.frequency.setValueAtTime(freq[0], audioContext.currentTime)

  // 设置音量包络
  gainNode.gain.setValueAtTime(0.1, audioContext.currentTime)
  gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.3)

  oscillator.start(audioContext.currentTime)
  oscillator.stop(audioContext.currentTime + 0.3)
}

// 获取事件的clientX，统一处理鼠标和触摸事件
const getClientX = (e: MouseEvent | TouchEvent): number => {
  if ('touches' in e && e.touches.length > 0) {
    return e.touches[0].clientX
  }
  return (e as MouseEvent).clientX
}

// 获取事件的clientY
const getClientY = (e: MouseEvent | TouchEvent): number => {
  if ('touches' in e && e.touches.length > 0) {
    return e.touches[0].clientY
  }
  return (e as MouseEvent).clientY
}

// 计算相对于滑块轨道的位置
const getRelativeX = (clientX: number): number => {
  if (!sliderTrack.value) return 0
  const rect = sliderTrack.value.getBoundingClientRect()
  return clientX - rect.left
}

// 防机器人检测函数
const detectBot = (): { isBot: boolean; reason: string; confidence: number } => {
  if (!props.enableBotDetection) {
    return { isBot: false, reason: '', confidence: 0 }
  }

  // 如果没有真正拖拽，跳过机器人检测
  if (!hasActuallyDragged.value) {
    return { isBot: false, reason: '', confidence: 0 }
  }

  const dragDuration = dragEndTime.value - dragStartTime.value
  const points = trackPoints.value
  let suspicionScore = 0
  let reasons: string[] = []

  // 检测1: 拖拽时间异常
  if (dragDuration < props.minDragTime) {
    suspicionScore += 30
    reasons.push('拖拽时间过短')
  }

  if (dragDuration > props.maxDragTime) {
    suspicionScore += 20
    reasons.push('拖拽时间过长')
  }

  // 检测2: 轨迹点数量异常
  if (points.length < props.minTrackPoints) {
    suspicionScore += 25
    reasons.push('轨迹点数过少')
  }

  // 检测3: 完美直线移动（机器人特征）
  const yVariance = calculateYVariance(points)
  if (yVariance < 2 && points.length > 20) {
    suspicionScore += 40
    reasons.push('移动轨迹过于完美')
  }

  // 检测4: 速度异常均匀（机器人特征）
  const velocityVariance = calculateVelocityVariance(points)
  if (velocityVariance < 0.1 && points.length > 15) {
    suspicionScore += 35
    reasons.push('移动速度过于均匀')
  }

  // 检测5: 立即开始拖拽（没有人类思考时间）
  const thinkTime = dragStartTime.value - componentMountTime.value
  if (thinkTime < 500) {
    suspicionScore += 30
    reasons.push('响应时间过快')
  }

  // 检测6: 频繁重试
  if (retryCount.value >= props.allowedRetries) {
    suspicionScore += 50
    reasons.push('重试次数过多')
  }

  // 检测7: 加速度模式分析
  if (hasRobotAccelerationPattern(points)) {
    suspicionScore += 45
    reasons.push('检测到机器人加速模式')
  }

  // 检测8: 鼠标轨迹分析
  const mousePatternScore = analyzeMousePattern(points)
  if (mousePatternScore > 0.7) {
    suspicionScore += 25
    reasons.push('鼠标移动模式异常')
  }

  // 机器人检测阈值为60分
  const isBot = suspicionScore >= 60
  const primaryReason = reasons.length > 0 ? reasons[0] : ''

  return {
    isBot,
    reason: primaryReason,
    confidence: Math.min(suspicionScore / 100, 1)
  }
}

// 分析鼠标移动模式
const analyzeMousePattern = (points: TrackPoint[]): number => {
  if (points.length < 5) return 0

  let perfectSteps = 0
  let totalSteps = 0

  for (let i = 1; i < points.length; i++) {
    const deltaX = Math.abs(points[i].x - points[i - 1].x)
    const deltaY = Math.abs(points[i].y - points[i - 1].y)

    // 检测是否为完美的水平或垂直移动
    if (deltaX > 0 && deltaY === 0) {
      perfectSteps++
    }
    totalSteps++
  }

  return totalSteps > 0 ? perfectSteps / totalSteps : 0
}

// 计算Y轴方差（检测是否为完美直线）
const calculateYVariance = (points: TrackPoint[]): number => {
  if (points.length < 2) return 0

  const avgY = points.reduce((sum, p) => sum + p.y, 0) / points.length
  const variance = points.reduce((sum, p) => sum + Math.pow(p.y - avgY, 2), 0) / points.length
  return Math.sqrt(variance)
}

// 计算速度方差（检测速度是否过于均匀）
const calculateVelocityVariance = (points: TrackPoint[]): number => {
  if (points.length < 3) return 1

  const velocities = points
    .slice(1)
    .map((p) => p.velocity)
    .filter((v) => v > 0)
  if (velocities.length < 2) return 1

  const avgVelocity = velocities.reduce((sum, v) => sum + v, 0) / velocities.length
  const variance =
    velocities.reduce((sum, v) => sum + Math.pow(v - avgVelocity, 2), 0) / velocities.length
  return Math.sqrt(variance) / avgVelocity
}

// 检测机器人加速度模式
const hasRobotAccelerationPattern = (points: TrackPoint[]): boolean => {
  if (points.length < 5) return false

  let constantAccelerationCount = 0

  for (let i = 2; i < points.length - 1; i++) {
    const v1 = points[i - 1].velocity
    const v2 = points[i].velocity
    const v3 = points[i + 1].velocity

    if (v1 > 0 && v2 > 0 && v3 > 0) {
      const a1 = v2 - v1
      const a2 = v3 - v2

      // 如果加速度变化过小，可能是机器人
      if (Math.abs(a1 - a2) < 0.1) {
        constantAccelerationCount++
      }
    }
  }

  // 如果超过70%的点都有恒定加速度，可能是机器人
  return constantAccelerationCount / Math.max(1, points.length - 4) > 0.7
}

// 记录轨迹点
const recordTrackPoint = (clientX: number, clientY: number): void => {
  const currentTime = Date.now()
  const x = getRelativeX(clientX)
  const y = clientY

  let velocity = 0
  let acceleration = 0
  let deltaTime = 0

  if (trackPoints.value.length > 0) {
    const lastPoint = trackPoints.value[trackPoints.value.length - 1]
    deltaTime = currentTime - lastPoint.timestamp

    if (deltaTime > 0) {
      const distance = Math.sqrt(Math.pow(x - lastPoint.x, 2) + Math.pow(y - lastPoint.y, 2))
      velocity = distance / deltaTime

      // 计算加速度
      if (trackPoints.value.length > 1) {
        acceleration = (velocity - lastPoint.velocity) / deltaTime
      }
    }
  }

  trackPoints.value.push({
    x,
    y,
    timestamp: currentTime,
    deltaTime,
    velocity,
    acceleration
  })
}

// 开始拖拽
const startDrag = (e: MouseEvent | TouchEvent) => {
  if (props.disabled || isSuccess.value || botDetected.value) return

  const clientX = getClientX(e)
  const clientY = getClientY(e)
  const relativeX = getRelativeX(clientX)

  isDragging.value = true
  initialMouseX.value = clientX
  startX.value = relativeX - sliderLeft.value
  dragStartTime.value = Date.now()

  // 重置轨迹记录和拖拽状态
  trackPoints.value = []
  userInteractionStarted.value = true
  hasActuallyDragged.value = false

  // 记录初始位置
  recordTrackPoint(clientX, clientY)
  lastPosition.value = { x: clientX, y: clientY }

  // 发出开始拖拽事件
  emit('start-drag')

  // 添加全局事件监听器
  document.addEventListener('mousemove', handleMouseMove, { passive: false })
  document.addEventListener('mouseup', handleMouseUp, { passive: false })
  document.addEventListener('touchmove', handleTouchMove, { passive: false })
  document.addEventListener('touchend', handleTouchEnd, { passive: false })

  // 阻止默认行为和事件冒泡
  e.preventDefault()
  e.stopPropagation()

  // 添加body样式防止页面滚动
  document.body.style.userSelect = 'none'
  document.body.style.webkitUserSelect = 'none'
}

const handleMouseDown = (e: MouseEvent) => startDrag(e)
const handleTouchStart = (e: TouchEvent) => startDrag(e)

// 拖拽移动
const moveDrag = (e: MouseEvent | TouchEvent) => {
  if (!isDragging.value || !sliderTrack.value) return

  const clientX = getClientX(e)
  const clientY = getClientY(e)
  const deltaX = clientX - initialMouseX.value
  const newLeft = Math.max(0, Math.min(deltaX, trackWidth.value - buttonWidth.value))

  // 检测是否真正进行了拖拽（移动距离超过5像素才算真正拖拽）
  if (Math.abs(deltaX) > 5) {
    hasActuallyDragged.value = true
  }

  // 记录轨迹点
  recordTrackPoint(clientX, clientY)
  lastPosition.value = { x: clientX, y: clientY }

  // 直接同步更新位置，不使用requestAnimationFrame避免延迟
  sliderLeft.value = newLeft
  const currentProgress = (newLeft / (trackWidth.value - buttonWidth.value)) * 100
  emit('change', Math.max(0, Math.min(100, currentProgress)))

  e.preventDefault()
}

const handleMouseMove = (e: MouseEvent) => moveDrag(e)
const handleTouchMove = (e: TouchEvent) => moveDrag(e)

// 结束拖拽
const endDrag = () => {
  if (!isDragging.value) return

  isDragging.value = false
  dragEndTime.value = Date.now()

  // 发出结束拖拽事件
  emit('end-drag')

  // 进行机器人检测
  const botCheck = detectBot()

  if (botCheck.isBot) {
    // 检测到机器人行为
    botDetected.value = true
    retryCount.value++

    // 重置状态
    if (props.resetOnFail) {
      sliderLeft.value = 0
    }
    isSuccess.value = false

    botDetectionReason.value = botCheck.reason

    // 震动和声音反馈
    vibrate([100, 50, 100])
    playSound('warning')

    emit('bot-detected', botCheck.reason, {
      confidence: botCheck.confidence,
      trackPoints: trackPoints.value.length,
      dragDuration: dragEndTime.value - dragStartTime.value,
      retryCount: retryCount.value
    })
    emit('fail')
    emit('retry', retryCount.value)

    console.warn(
      `机器人检测: ${botCheck.reason} (置信度: ${Math.round(botCheck.confidence * 100)}%)`
    )

    // 3秒后允许重试
    setTimeout(() => {
      botDetected.value = false
    }, 3000)
  } else {
    // 检查是否滑动到设定的阈值
    const maxLeft = trackWidth.value - buttonWidth.value
    const currentProgress = (sliderLeft.value / maxLeft) * 100

    if (currentProgress >= props.threshold) {
      // 验证成功
      isSuccess.value = true
      sliderLeft.value = maxLeft
      retryCount.value = 0 // 重置重试计数

      // 震动和声音反馈
      vibrate([50, 25, 50, 25, 100])
      playSound('success')

      emit('success')

      // 自动重置
      if (props.autoReset) {
        setTimeout(() => {
          reset()
        }, props.autoResetDelay)
      }
    } else {
      // 验证失败，平滑重置位置
      retryCount.value++

      // 震动反馈
      vibrate(200)
      playSound('fail')

      if (props.resetOnFail) {
        const resetAnimation = () => {
          if (sliderLeft.value > 0) {
            sliderLeft.value = Math.max(0, sliderLeft.value - 10)
            requestAnimationFrame(resetAnimation)
          }
        }
        resetAnimation()
      }

      emit('fail')
      emit('retry', retryCount.value)
    }
  }

  // 移除事件监听器和body样式
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
  document.removeEventListener('touchmove', handleTouchMove)
  document.removeEventListener('touchend', handleTouchEnd)

  document.body.style.userSelect = ''
  document.body.style.webkitUserSelect = ''
}

const handleMouseUp = () => endDrag()
const handleTouchEnd = () => endDrag()

// 重置验证
const reset = () => {
  isSuccess.value = false
  sliderLeft.value = 0
  isDragging.value = false
  botDetected.value = false
  botDetectionReason.value = ''
  trackPoints.value = []
  retryCount.value = 0
  userInteractionStarted.value = false
  hasActuallyDragged.value = false
  componentMountTime.value = Date.now()
  emit('reset')
}

// 获取机器人检测数据
const getBotDetectionData = () => ({
  retryCount: retryCount.value,
  trackPoints: trackPoints.value.length,
  dragDuration: dragEndTime.value - dragStartTime.value,
  botDetected: botDetected.value,
  botDetectionReason: botDetectionReason.value,
  averageVelocity:
    trackPoints.value.length > 0
      ? trackPoints.value.reduce((sum, p) => sum + p.velocity, 0) / trackPoints.value.length
      : 0,
  yVariance: calculateYVariance(trackPoints.value),
  velocityVariance: calculateVelocityVariance(trackPoints.value)
})

// 初始化
onMounted(async () => {
  componentMountTime.value = Date.now()

  await nextTick()
  if (sliderTrack.value) {
    trackWidth.value = sliderTrack.value.offsetWidth

    // 监听窗口大小变化
    const resizeObserver = new ResizeObserver(() => {
      if (sliderTrack.value) {
        trackWidth.value = sliderTrack.value.offsetWidth
      }
    })
    resizeObserver.observe(sliderTrack.value)
  }
})

// 清理事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', handleMouseUp)
  document.removeEventListener('touchmove', handleTouchMove)
  document.removeEventListener('touchend', handleTouchEnd)

  document.body.style.userSelect = ''
  document.body.style.webkitUserSelect = ''
})

// 监听禁用状态变化
watch(
  () => props.disabled,
  (newVal) => {
    if (newVal && isDragging.value) {
      endDrag()
    }
  }
)

// 暴露方法
defineExpose({
  reset,
  getBotDetectionData,
  // 新增方法
  getCurrentProgress: () => progress.value,
  isVerified: () => isSuccess.value,
  getRetryCount: () => retryCount.value,
  isBotDetected: () => botDetected.value
})
</script>

<style scoped lang="scss">
.slider-verify-container {
  display: inline-block;
  width: 100%;
}

.slider-header {
  margin-bottom: 8px;
}

.slider-track {
  position: relative;
  width: v-bind('props.width + "px"');
  height: v-bind('props.height + "px"');
  background-color: v-bind('props.trackColor');
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  overflow: hidden;
  user-select: none;
  -webkit-user-select: none;
  touch-action: none;
}

.slider-progress {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  border-radius: 6px;
  transition: none;
}

.progress-content {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  z-index: 1;
  display: flex;
  align-items: center;
  padding: 0 8px;
}

.slider-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 14px;
  color: v-bind('props.textColor');
  pointer-events: none;
  transition: color 0.3s ease;
  z-index: 1;
  white-space: nowrap;

  &.text-success {
    color: v-bind('props.successTextColor');
    font-weight: 500;
  }
}

.slider-button {
  position: absolute;
  top: 0;
  left: 0;
  width: v-bind('buttonWidth + "px"');
  height: 100%;
  border-radius: 6px;
  cursor: grab;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  transition:
    box-shadow 0.2s ease,
    border-color 0.2s ease;
  will-change: transform;

  &:hover:not(.slider-success):not(.slider-dragging):not(.slider-disabled) {
    border-color: v-bind('props.buttonActiveBorderColor');
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  }

  &.slider-dragging {
    cursor: grabbing;
    box-shadow: 0 4px 16px rgba(64, 158, 255, 0.4);
    // 拖拽时禁用所有过渡效果，确保立即响应
    transition: none;
  }

  &.slider-success {
    cursor: default;

    &:hover {
      box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);
    }
  }

  &.slider-disabled {
    cursor: not-allowed;
    opacity: 0.6;
  }
}

.track-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
  z-index: 1;
}

.slider-icon {
  width: 16px;
  height: 16px;
  color: #909399;
  transition:
    color 0.2s ease,
    transform 0.2s ease;

  &.rotating {
    animation: rotate 1s linear infinite;
  }

  .slider-success & {
    color: #fff;
  }

  .slider-dragging & {
    color: #409eff;
  }
}

.bot-warning {
  margin-top: 8px;

  .default-bot-warning {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 8px 12px;
    background-color: #fef0f0;
    border: 1px solid #fde2e2;
    border-radius: 4px;
    color: #f56c6c;
    font-size: 12px;

    .warning-icon {
      margin-right: 6px;
      font-size: 14px;
    }
  }
}

.slider-footer {
  margin-top: 8px;

  .progress-info {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 12px;
    color: #666;

    .progress-text {
      min-width: 60px;
    }

    .progress-bar {
      flex: 1;
      height: 4px;
      background: #f0f0f0;
      border-radius: 2px;
      overflow: hidden;

      .progress-fill {
        height: 100%;
        background: v-bind('props.progressColor');
        border-radius: 2px;
        transition: width 0.3s ease;
      }
    }
  }
}

.slider-help {
  margin-top: 6px;

  .help-content {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 11px;
    color: #999;

    .help-icon {
      font-size: 12px;
    }
  }
}

// 动画
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 机器人检测提示动画
.bot-warning-enter-active,
.bot-warning-leave-active {
  transition: all 0.3s ease;
}

.bot-warning-enter-from,
.bot-warning-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

// 移动端优化
@media (max-width: 768px) {
  .slider-button {
    &:hover {
      border-color: v-bind('props.buttonBorderColor');
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    }
  }
}

// 无障碍支持
@media (prefers-reduced-motion: reduce) {
  .slider-button {
    transition: none;
  }

  .bot-warning-enter-active,
  .bot-warning-leave-active {
    transition: none;
  }

  .slider-icon.rotating {
    animation: none;
  }
}
</style>
